package com.cml.batisext.core.repository.mybatis.base.sqlprovider;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import com.cml.batisext.core.repository.mybatis.annotations.DbField;
import com.cml.batisext.core.repository.mybatis.annotations.DbTable;
import com.cml.batisext.core.repository.mybatis.base.BaseDao;
import com.cml.batisext.core.repository.mybatis.base.BaseDaoSqlProvider;
import com.cml.batisext.util.Contants;

/**
 * 通用接口的insertBatch方法的sql生成器
 * @author lwh
 *
 */
public class BaseDaoInsertBatchSqlProvider extends BaseDaoSqlProvider {

    @Override
    public String doBuildSql(Map<String, Object> params, Class<?> beanType) throws Exception {

        String tableName = beanType.getAnnotation(DbTable.class).table();

        List<Field> fields = getAllDbField(beanType);
        String sql = "";
        String sqlField = "  ";
        String sqlValues = "  ";
        String sqlValue = "  ";
        String tmpColumnName = null;
        Class<?> tmpColumnType = null;
        Object fieldValue = null;
        List<Object> list = (List<Object>) params.get(BaseDao.LIST_PARAM_NAME);
        for (Object listobj : list) {
            sqlField = "  ";
            sqlValues = "  ";
            for (Field f : fields) {

                DbField field = f.getAnnotation(DbField.class);
                //只对标注了为数据库字段的属性进行处理
                if (field == null) {
                    continue;
                }

                tmpColumnName = getColumnName(f, field);
                //新增时id由数据库自增
                if ("`id`".equals(tmpColumnName)) {
                    continue;
                }
                tmpColumnType = getColumnType(f, field);
                fieldValue = getColumnValue(listobj, f, beanType);
                //默认插入version=1
                if ("`version`".equals(tmpColumnName)) {
                	fieldValue = Contants.VERSION ;
                }
                
                sqlField += tmpColumnName + ",";
                 
                sqlValues += setupFieldValue(tmpColumnType, fieldValue) + ",";
                
            }
            sqlValue += "(" + sqlValues.substring(0, sqlValues.length() - 1) + "),";
        }

        sql = "insert into " + tableName + "(" + sqlField.substring(0, sqlField.length() - 1) + ") values" + sqlValue.substring(0, sqlValue.length() - 1);
        return sql;
    }

}
